import os
import sys
import subprocess
import shutil


def clone_or_update_repo(repo_url, dest_dir, username, password):
    auth_url = repo_url.replace("http://", f"http://{username}:{password}@")
    if os.path.exists(dest_dir):
        try:
            print(f"Updating repository in {dest_dir} ...")
            subprocess.run(["git", "-C", dest_dir, "pull"], check=True)
            print("Repository updated successfully.")
        except subprocess.CalledProcessError:
            print("Error occurred while updating the repository.")
    else:
        command = ["git", "clone", auth_url, dest_dir]
        try:
            subprocess.run(command, check=True)
            print(f"Cloned repository into {dest_dir}")
        except subprocess.CalledProcessError:
            print("Error occurred while cloning the repository.")


def setup_doc_structure(repo_dir, base_dir):
    """Sets up the Sphinx documentation structure in the doc project."""
    src_dir = os.path.join(repo_dir, "src")
    target_src_dir = os.path.join(base_dir, "src")

    # Remove existing src directory if present
    if os.path.exists(target_src_dir):
        shutil.rmtree(target_src_dir)

    # Copy src directory to doc project
    shutil.copytree(src_dir, target_src_dir)
    print(f"Copied src directory to {base_dir}")

    # Copy README.md to doc project
    readme_path = os.path.join(repo_dir, "README.md")
    shutil.copyfile(readme_path, os.path.join(target_src_dir, "README.md"))


if __name__ == "__main__":
    repo_url = "http://xxx/yyy.git"
    repo_name = "yyy"
    base_dir = os.path.dirname(os.path.abspath(__file__))
    repo_dir = os.path.join(base_dir, repo_name)

    # Step 1: Clone the repository into the doc directory
    username = ''
    password = ''
    if not username or not password:
        print("Error: Missing username and password")
        sys.exit(1)
    clone_or_update_repo(repo_url, repo_dir, username, password)

    # Step 2: Set up the documentation structure
    setup_doc_structure(repo_dir, base_dir)

    # Step 3: Run the Sphinx documentation generation script
    try:
        subprocess.run(["python", "auto_generate.py"], cwd=base_dir, check=True)
        print("Documentation generated successfully.")
    except subprocess.CalledProcessError:
        print("Error occurred while generating documentation.")
